<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      :upload-before="uploadBefore"
      ref="crud"
      @row-update="rowUpdate"
      :upload-after="uploadAfter"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad">
      <template #menu="{row,index,size}">
        <el-button type="text"
                   icon="el-icon-view"
                   size="small"
                   plain
                   @click="batchShow(row)">查看
        </el-button>
      </template>
      <template slot="excelTemplateForm">
        <el-button type="primary" @click="handleTemplate">
          点击下载<i class="el-icon-download el-icon--right"></i>
        </el-button>
      </template>
      <template slot="errorDataTemplateForm">
        <el-button v-if="this.showOrHide" type="warning" @click="downloadErrorData">
          点击下载<i class="el-icon-download el-icon--right"></i>
        </el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.purchaseBatch_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
      title="批次详情"
      :visible.sync="batchDetail"
      :fullscreen="false"
      append-to-body center
      destroy-on-close
      width="1100px"
      height="auto"
      @close="clearForm">
      <avue-form :option="option" v-model="form">

      </avue-form>

      <purchase-batch-detail :batch-name="batchName">

      </purchase-batch-detail>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/businessTwo/purchaseBatch";
import detailOption from "@/const/businessTwo/purchaseBatchDetail";
import {mapGetters} from "vuex";
import {exportBlob} from "@/api/common";
import {getToken} from "@/util/auth";
import PurchaseBatchDetail from "@/views/businessTwo/purchaseBatchDetail";

export default {
  components: {PurchaseBatchDetail},
  data() {
    return {
      batchName: '',
      pageSub: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      detailData: [],
      detailForm: {},
      detailOption: detailOption,
      batchDetail: false,
      templateName: '集采批次模板.xlsx',
      showOrHide: true,
      form: {id: ''},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        submitBtn: false,
        columnBtn: false,
        emptyBtn: false,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 120,

        border: true,
        index: true,
        viewBtn: true,
        selection: false,
        dialogClickModal: false,
        column: [
          {
            label: "id",
            prop: "id",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,
          },
          {
            label: "批次名称",
            prop: "batchName",
            search: true,
            disabled: false,
            rules: [
              {
                required: true,
                message: "请输入批次名称",
                trigger: "blur",
              },
            ],
            spans: 24,
          },
          {
            label: "模板文件",
            prop: "imgUrl",
            type: "upload",
            span: 24,
            display: true,
            drag: true,
            viewDisplay: false,
            loadText: '模板上传中，请稍等',
            fileText: '选取导入数据文件',
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/purchaseBatchDetail/import",
            data: {
              batchId: '',
            },
            hide: true,
            success(res, file, fileList) {
              console.log(res)
            }
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            viewDisplay: false,
            hide: true,
            display: true,
            span: 12,
          },
          {
            label: '错误数据下载',
            prop: 'errorDataTemplate',
            formslot: true,
            viewDisplay: false,
            addDisplay: false,
            hide: true,
            editDisplay: false,
            span: 12,
            display: true,
          },
          {
            label: "批次月份",
            prop: "month",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,
          },
          {
            label: "地市",
            prop: "city",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,
          },
          {
            label: "状态",
            prop: "status",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,

          },
          {
            label: "创建部门",
            prop: "createDept",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,

          },
          {
            label: "创建人",
            prop: "createUser",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,

          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,

          },
          {
            label: "更新人",
            prop: "updateUser",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,

          },
          {
            label: "更新时间",
            prop: "updateTime",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,
          },
          {
            label: "删除标识",
            prop: "isDeleted",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            display: false,

          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.purchaseBatch_add, true),
        viewBtn: this.vaildData(this.permission.purchaseBatch_view, false),
        delBtn: this.vaildData(this.permission.purchaseBatch_delete, false),
        editBtn: this.vaildData(this.permission.purchaseBatch_edit, true)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    clearForm() {
      this.findObject(this.option.column, 'errorDataTemplate').display = true;
      this.findObject(this.option.column, 'excelTemplate').display = true;
      this.findObject(this.option.column, 'imgUrl').display = true;
      this.findObject(this.option.column, 'batchName').disabled = false;

    },
    batchShow(row) {
      this.batchName = row.batchName;
      this.form.batchName = this.batchName;
      this.findObject(this.option.column, 'errorDataTemplate').display = false;
      this.findObject(this.option.column, 'batchName').disabled = true;
      this.findObject(this.option.column, 'excelTemplate').display = false;
      this.findObject(this.option.column, 'imgUrl').display = false;
      this.batchDetail = true;
    },
    handleTemplate() {
      exportBlob(`/api/purchaseBatchDetail/download?${this.website.tokenHeader}=${getToken()}&templateName=${this.templateName}`).then((response) => {
        if (response.data.size > 0) {
          let url = window.URL.createObjectURL(response.data);
          let a = document.createElement("a");
          document.body.appendChild(a);
          a.href = url;
          a.download = this.templateName;
          a.click();
          window.URL.revokeObjectURL(url);
        } else {
          this.$message.warning('模板文件不存在!');
        }
      });
    },
    downloadErrorData() {
      exportBlob(`/api/purchaseBatchDetail/downloadErrorData?${this.website.tokenHeader}=${getToken()}`).then((response) => {
        if (response.data.size > 0) {
          let url = window.URL.createObjectURL(response.data);
          let a = document.createElement("a");
          document.body.appendChild(a);
          a.href = url;
          a.download = "集采批次管理批量导入错误明细.xlsx";
          a.click();
          window.URL.revokeObjectURL(url);

        } else {
          this.$message.warning('模板文件不存在!');
        }
      });
    },
    uploadBefore(file, done, loading, column) {
      column.data.batchId = this.form.id;
      done();
    },
    uploadAfter(res, done) {
      if (res.success) {
        this.form.id = res.data;
        //console.log('form',this.form.msg);
        const regex = /导入失败:(\d+)条/;
        const matches = res.msg.match(regex);
        const count = parseInt(matches[1]);
        console.log(count)
        if (count > 0) {
          this.findObject(this.option.column, "errorDataTemplate").addDisplay = true;
          this.findObject(this.option.column, "errorDataTemplate").editDisplay = true;
          this.$message({
            type: "warning",
            message: "存在错误数据、下载查看错误信息"
          });
        } else {
          this.$message({
            type: "success",
            message: res.msg
          });
        }


      }
      done();
    },
    rowSave(row, done, loading) {
      if (row.id === undefined || row.id === '') {
        this.$message({
          type: "error",
          message: "请上传模板文件！"
        });
        loading();
      } else {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.findObject(this.option.column, "errorDataTemplate").addDisplay = false;
          this.findObject(this.option.column, "errorDataTemplate").editDisplay = false;
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      }
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.findObject(this.option.column, "errorDataTemplate").addDisplay = false;
        this.findObject(this.option.column, "errorDataTemplate").editDisplay = false;
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
